# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

colorData <- read.csv(opt$sc, header = T, stringsAsFactors = F) %>%
  select(c("ClassNote", "col"))

sampleColDf <- colorData
sampleCols <- sampleColDf %>%
  deframe()

sampleColDf

parameterData <- read_csv("PCA_with_All_Samples_R2.csv")

plotData <- read_csv("PCA_with_All_Samples_Score.csv") %>%
  left_join(sampleInfo, by = "SampleID")

xBreaks <- seq(-20, 20, by = 10)

fileName <- paste0("PCA_with_All_Samples_First2PCs.pdf")

impoPc1 <- parameterData[1, "PC1"]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- parameterData[1, "PC2"]
impoPc2 <- round(impoPc2 * 100, 2)

noQcData <- plotData %>%
  filter(ClassNote != "QC")

noQcData

p <- ggplot(plotData, mapping = aes(x = PC1, y = PC2, color = ClassNote)) +
  xlab(paste("PC1(", impoPc1, "%)", sep = "")) +
  ylab(paste("PC2(", impoPc2, "%)", sep = "")) +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 9, hjust = 1, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'right',
        axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 8), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
  ) +
  #0 line
  geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
  #point
  stat_ellipse(data = noQcData, aes(fill = ClassNote), colour = NA, size = 0.3, level = 0.95, type = "norm",
               geom = "polygon", alpha = 0.1, show.legend = F) +
  geom_point(size = 4, stroke = 0) +
  #lengend
  scale_colour_manual("", values = sampleCols) +
  scale_fill_manual("", values = sampleCols) +
  scale_x_continuous(breaks = xBreaks)
ggsave(limitsize = FALSE, fileName, p, width = 5, height = 4)




